/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package loginbean;

/**
 *
 * @author vexdan
 */
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DBManager {

    private static DBManager instance = null;
    private static String driverName = "com.mysql.jdbc.Driver";
    private static String jdbcProtocol = "jdbc:mysql:";
    private String hostName = "localhost";
    private String port = "3306";
    private static String connectionString = "mydb";
    private static Driver registeredDriver = null;
    private Connection connection = null;
    private String userName = "root";
    private String password = "";

    static {
        registerDriver();
    }

    public static DBManager getInstance() {
        if (instance == null) {
            instance = new DBManager();
        }
        return instance;
    }

    private static void registerDriver() {
        if (registeredDriver != null) {
            return;
        }
        try {
            Class driver_cls = Class.forName(driverName);
            registeredDriver = (Driver) driver_cls.newInstance();
            DriverManager.registerDriver(registeredDriver);
            System.out.println("got connection in DBManager class");
        } catch (Exception e) {
            System.out.println("ERROR -  in registerDriver() of DBManager.");
        }
    }
//call new DBManager().getDatabaseConnection();

    public Connection getDatabaseConnection() throws Exception {
        try {
            if (connection == null || connection.isClosed()) {
                String con_url = jdbcProtocol + "//" + hostName + ":" + port + "/" + connectionString;
                connection = DriverManager.getConnection(con_url, userName, password);
            }
        } catch (SQLException e) {
            throw new Exception("ERROR - getDatabaseConnection() Method Failed - " + e.getMessage());
        }
        return connection;
    }
}
